from __future__ import annotations

import threading
from typing import Optional
import pystray  # type: ignore
from PIL import Image, ImageDraw  # type: ignore


class TrayIcon:
    """系统托盘图标管理"""

    def __init__(self, controller) -> None:
        self.controller = controller
        self.icon: Optional[pystray.Icon] = None
        self._create_icon()

    def _create_icon(self) -> None:
        """创建托盘图标"""
        try:
            image = Image.open("game.ico")
        except FileNotFoundError:
            image = self._create_default_icon()

        menu = pystray.Menu(
            pystray.MenuItem(
                "连击",
                self._toggle_click,
                checked=lambda item: self.controller.click_enabled,
            ),
            pystray.Menu.SEPARATOR,
            pystray.MenuItem("退出", self._exit_app),
        )

        self.icon = pystray.Icon(
            "click",
            image,
            "连击助手",
            menu
        )

    def _create_default_icon(self) -> Image.Image:
        """创建默认图标"""
        size = 64
        image = Image.new('RGBA', (size, size), (0, 0, 0, 0))
        draw = ImageDraw.Draw(image)

        # 绘制简单的游戏手柄形状
        draw.ellipse([8, 20, 56, 44], fill=(50, 50, 50), outline=(100, 100, 100), width=2)
        draw.ellipse([12, 24, 20, 32], fill=(200, 50, 50))
        draw.ellipse([44, 24, 52, 32], fill=(50, 200, 50))
        draw.ellipse([28, 28, 36, 36], fill=(100, 100, 200))

        return image


    def _toggle_click(self, icon: pystray.Icon, item: pystray.MenuItem) -> None:
        """切换连击状态"""
        self.controller.toggle_click()

    def _exit_app(self, icon: pystray.Icon, item: pystray.MenuItem) -> None:
        """退出应用"""
        self.controller.stop_and_exit()

    def start(self) -> None:
        """启动托盘图标"""
        if self.icon:
            threading.Thread(target=self.icon.run, daemon=True).start()

    def stop(self) -> None:
        """停止托盘图标"""
        if self.icon:
            try:
                self.icon.stop()
            except (OSError, RuntimeError):
                pass

    def update_status(self) -> None:
        """更新状态显示"""
        if self.icon:
            status = []
            if self.controller.click_enabled:
                status.append("连击")

            tooltip = "连击助手"
            if status:
                tooltip += f" - {'+'.join(status)}"

            self.icon.title = tooltip
